package com.test.huffmanserver.utils;

import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class FileUtils {

    public static final String ZipPath="D:\\huffmanTree\\huffman-tree-curriculum\\huffman-server\\src\\main\\resources\\Zip\\";
    public static final String Original="D:\\huffmanTree\\huffman-tree-curriculum\\huffman-server\\src\\main\\resources\\Original\\";
    public static final String UnZipPath="D:\\huffmanTree\\huffman-tree-curriculum\\huffman-server\\src\\main\\resources\\UnZip\\";

    public static String upload(MultipartFile file) {

        //传输为空文件
        if(file.isEmpty())
        {
           return null;
        }

        //获取原始名字
        String fileName=file.getOriginalFilename();

        //文件路径

        //IO流文件
        File dest=new File(Original+fileName);

        //如果File文件夹不存在
        if(!dest.getParentFile().exists())
        {
            dest.getParentFile().mkdirs();//创建文件夹
        }
        try {//复制文件
            file.transferTo(dest);//文件存入服务器本地

        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        return fileName;//返回文件名
    }


    public static ResponseEntity<byte[]> download(String fileName,String path){

        FileSystemResource file=new FileSystemResource(path+fileName);

        HttpHeaders headers=new HttpHeaders();//请求头
        headers.add("Content-Disposition","attachment;");

        try {
            return new ResponseEntity<>(readFileToByteArray(path+fileName),headers, HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] readFileToByteArray(String file) throws IOException {
        File f=new File(file);
        byte[] buffer=new byte[(int) f.length()];
        FileInputStream in=new FileInputStream(file);
        int offSet=0;
        int numRead=0;
        while (offSet<buffer.length&&(
                numRead=in.read(buffer,offSet, buffer.length-offSet))>=0){
            offSet+=numRead;
        }
        if(offSet!=buffer.length){
            System.out.println("文件转换成字节出错");
        }
        in.close();
        return buffer;
    }
//    public static void download(String fileName, String Bpath, HttpServletResponse response){
//
//        Path path= Paths.get(Bpath,fileName);
//
//        if (Files.exists(path)){
//            response.setContentType("application/binary");
//            response.addHeader("Content-Disposition","attachment;");
//            try {
//                Files.copy(path,response.getOutputStream());
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//    }

}
